package com.learning.dubbo.features.async.provider;

import com.learning.dubbo.features.async.api.GreetingsService;
import org.apache.dubbo.rpc.AsyncContext;
import org.apache.dubbo.rpc.RpcContext;

import java.util.concurrent.CompletableFuture;

/**
 * ClassName: GreetingsServiceImpl
 * Description: 服务实现
 * Date: 2020/6/15 13:43 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class GreetingsServiceImpl implements GreetingsService {
    @Override
    public String sayHi(String name) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hi, " + name;
    }

    @Override
    public CompletableFuture<String> sayHello(String name) {
        RpcContext savedContext = RpcContext.getContext();
        // 建议为 supplyAsync 提供自定义线程池，避免使用JDK公用线程池
        // 通过 return CompletableFuture.supplyAsync() ，业务执行已从Dubbo线程切换到业务线程，避免了对Dubbo线程池的阻塞
        return CompletableFuture.supplyAsync(() -> {
            System.out.println(savedContext.getAttachment("consumerkey1"));
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "async response from provider.";
        });
    }

    @Override
    public String sayHello2(String name) {
        final AsyncContext asyncContext = RpcContext.startAsync();
        new Thread(() -> {
            // 如果要使用上下文，则必须要放在第一句执行
            asyncContext.signalContextSwitch();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 写回响应
            asyncContext.write("Hello " + name + ", response from provider.");
        }).start();
        return null;
    }
}